package com.shibei.forumv2.controller;

import com.shibei.forumv2.common.AppResult;
import com.shibei.forumv2.common.ResultCode;
import com.shibei.forumv2.model.User;
import com.shibei.forumv2.services.IUserService;
import com.shibei.forumv2.services.impl.IUserServiceImpl;
import com.shibei.forumv2.utils.MD5Util;
import com.shibei.forumv2.utils.StringUtil;
import com.shibei.forumv2.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名")@RequestParam("username")@NonNull String username,
                              @ApiParam("昵称")@RequestParam("nickname")@NonNull String nickname,
                              @ApiParam("密码")@RequestParam("password")@NonNull String password,
                              @ApiParam("确认密码")@RequestParam("passwordRepeat")@NonNull String passwordRepeat){

        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(nickname)||StringUtil.isEmpty(password)||StringUtil.isEmpty(passwordRepeat))
        {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        String salt = UUIDUtil.UUID_32();
        String encryPassword = MD5Util.md5Salt(salt, password);
        user.setPassword(encryPassword);
        user.setSalt(salt);

        userService.createNomalUser(user);

        return AppResult.success();
    }


}
